package copy.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import copy.com.R;
import copy.dao.DishDao;
import copy.dto.DishDto;
import copy.pojo.Category;
import copy.pojo.Dish;
import copy.pojo.DishFlavor;
import copy.service.CategoryService;
import copy.service.DishFlavorService;
import copy.service.DishService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 *
 **/

@Service
public class DishServiceImpl extends ServiceImpl<DishDao, Dish> implements DishService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;

    /**
     * 保存菜品数据和口味数据
     *
     * @param dishDto
     */
    @Transactional
    public void saveWithFlavors(DishDto dishDto) {
        //保存dish的数据
        this.save(dishDto);
        //保存口味数据 数据有 但是缺少dish_id
        Long dishId = dishDto.getId();
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors = flavors.stream().map((itm) -> {
            itm.setDishId(dishId);
            return itm;
        }).collect(Collectors.toList());
        dishFlavorService.saveBatch(flavors);
    }

    /**
     * Page<DishDto> redissource = (Page<DishDto>) redisTemplate.opsForValue().get(dishkey);
     * if (redissource!=null) {
     * return redissource;
     * }
     * 菜品分页 查询
     * dish_1_1
     */
    @Transactional
    public Page<DishDto> Ipage(int page, int pageSize, String name) {
        String dishkey = "dish_" + page + "_1";
        String s = redisTemplate.opsForValue().get(dishkey);
        if (s != null) {
            Page<DishDto> p = JSON.parseObject(s, new TypeReference<Page<DishDto>>() {
            });
            return p;
        }
        //分页构造器
        Page<Dish> dishPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(name), Dish::getName, name).orderByDesc(Dish::getUpdateTime);
        this.page(dishPage, queryWrapper);
        //数据缺少category字段
        Page<DishDto> dishDtoPage = new Page<>();
        BeanUtils.copyProperties(dishPage, dishDtoPage, "records");
        List<Dish> records = dishPage.getRecords();
        List<DishDto> recordsPlus = records.stream().map((item) -> {
            //item即每一条口味数据 扩展新的对象来copy口味数据 和封装category name字段
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            Long categoryId = dishDto.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                dishDto.setCategoryName(category.getName());
            }
/*            Long dishID = dishDto.getId();
            LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(DishFlavor::getDishId, dishID).orderByDesc(DishFlavor::getCreateTime);
            List<DishFlavor> list = dishFlavorService.list(wrapper);
            dishDto.setFlavors(list);*/
            return dishDto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(recordsPlus);
        redisTemplate.opsForValue().set(dishkey, JSON.toJSONString(dishDtoPage), 30, TimeUnit.MINUTES);
        return dishDtoPage;
    }

    //根据id查询菜品数据和对应可能存在的口味u数据
    public DishDto qWithFlavorsBydishId(Long id) {
        //查询菜品数据
        Dish dish = this.getById(id);
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish, dishDto);

        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DishFlavor::getDishId, id);
        List<DishFlavor> list = dishFlavorService.list(wrapper);
        dishDto.setFlavors(list);
        return dishDto;
    }

    /**
     * 更新菜品的最后保存 先处理dish
     * 处理口味表中的数据 采用先删再存
     *
     * @param dishDto
     */
    public void updateDishWithFlavors(DishDto dishDto) {
        this.updateById(dishDto);
        LambdaQueryWrapper<DishFlavor> qu = new LambdaQueryWrapper<>();
        qu.eq(DishFlavor::getDishId, dishDto.getId());
        dishFlavorService.remove(qu);

        //  //保存口味数据 数据有 但是缺少dish_id
        Long dishId = dishDto.getId();
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors = flavors.stream().map((itm) -> {
            itm.setDishId(dishId);
            return itm;
        }).collect(Collectors.toList());
        dishFlavorService.saveBatch(flavors);

    }

    @Override
    public List<DishDto> listDishWithFlavors(Dish dish) {
        //查category_id 和status=1 的数据
        String key = "list_" + dish.getCategoryId() + "_$";
        String s = redisTemplate.opsForValue().get(key);
        if (s != null) {
          List<DishDto>SS=  JSON.parseObject(s, new TypeReference<List<DishDto>>() {
            });
            return SS;
        }
        LambdaQueryWrapper<Dish> dishQW = new LambdaQueryWrapper<>();
        dishQW.eq(Dish::getCategoryId, dish.getCategoryId()).eq(Dish::getStatus, 1).orderByDesc(Dish::getSort);
        List<Dish> dishlist = this.list(dishQW);
        //取出每一条dish数据 封装口味数据 使用DishDto来改造这个集合
        List<DishDto> dishDtoList = dishlist.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(DishFlavor::getDishId, dishId);
            List<DishFlavor> dishFlavors = dishFlavorService.list(queryWrapper);
            dishDto.setFlavors(dishFlavors);
            //取categoryName 存
            Category category = categoryService.getById(dish.getCategoryId());
            if (category != null) {
                dishDto.setCategoryName(category.getName());
            }
            return dishDto;
        }).collect(Collectors.toList());
        redisTemplate.opsForValue().set(key, JSON.toJSONString(dishDtoList), 30, TimeUnit.MINUTES);
        return dishDtoList;
    }
}
